import {getUserList, putUserFreeze, putUserDisabled} from '../../../api/admin/user.js'
import {useEffect, useState} from "react";
import {Table, Button, Tag, Badge, Image, Pagination, Form, Row, Col, Input, DatePicker, message} from 'antd';
import dayjs from 'dayjs';
import './user.less'
import {useNavigate} from "react-router-dom";

const User = () => {
    const [form] = Form.useForm();
    const {RangePicker} = DatePicker;
    const [list, setList] = useState([])
    const [pageSize, setPageSize] = useState(10)
    const [pageNum, setPageNum] = useState(1)
    const [total, setTotal] = useState(0)


    let [createdStartTime, setCreatedStartTime] = useState('')
    let [createdEndTime, setCreatedEndTime] = useState('')

    const onShowSizeChange = (current, pageSize) => {
        setPageNum(1)
        setPageSize(pageSize)
        getList(1, pageSize)
    }
    const onChange = (pageNum, pageSize) => {
        setPageNum(pageNum)
        getList(pageNum, pageSize)
    };

    useEffect(() => {
        getList(1, 10)
    }, [])

    const getList = (pageNum, pageSize) => {
        console.log(createdStartTime, createdEndTime);
        const list = {
            username: form.getFieldValue('username'),
            nickName: form.getFieldValue('nickName'),
            email: form.getFieldValue('email'),
            pageNum: pageNum,
            pageSize: pageSize
        }
        getUserList(list)
            .then(res => {
                setList(res.data.list)
                setPageSize(res.data.pageSize)
                setPageNum(res.data.pageNum)
                setTotal(res.data.total)
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const putFreezeList = (id) => {
        putUserFreeze({id: id})
            .then(res => {
                const {code} = res
                if (code === 200) {
                    message.success('冻结成功');
                    getList(1, pageSize)
                } else {
                    message.error('冻结失败');
                }
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const putDisabledList = (id, status) => {
        const list = {
            id,
            status
        }
        putUserDisabled(list)
            .then(res => {
                console.log(res, 'res')
                const {code} = res
                if (code === 200) {
                    message.success(status ? '停用成功' : '启用成功');
                    getList(1, pageSize)
                } else {
                    message.error(status ? '停用失败' : '启用失败');
                }
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const columns = [{
        title: '序号', align: 'center', width: 60, render: (text, record, index) => {
            return <>{index + 1}</>
        },
    }, {
        title: '昵称',
        dataIndex: 'nickName',
        key: 'nickName',
        width: 100,
        render: (text, record) => <a onClick={() => navigate(`/user/detail`, {state: {id: record.id}})}>{text}</a>,
    }, {
        title: '头像', dataIndex: 'headPic', key: 'headPic', width: 100, render: (text) => (<span>
          <Image
              width={60}
              height={60}
              src={text}
              fallback="http://localhost:9000/dev/err.png"
          />
        </span>)
    }, {
        title: '用户名', dataIndex: 'username', key: 'username', width: 160,
    }, {
        title: '电话', dataIndex: 'phoneNumber', key: 'phoneNumber', width: 160,
    }, {
        title: '邮箱', dataIndex: 'email', key: 'email', width: 200,
    }, {
        title: '状态', dataIndex: 'isFrozen', key: 'isFrozen', width: 80, render: (text) => (<span>

          {!text && <Badge status="success" text="正常"/>}
            {text && <Badge status="default" text="停用"/>}
        </span>)
    }, {
        title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 150, render: (text) => (<span>
          {dayjs(text).format("YYYY-MM-DD HH:mm:ss")}
        </span>)
    }, {
        title: '账号', dataIndex: 'isAdmin', key: 'isAdmin', width: 140, render: (text) => (<span>

          {text && <Tag color="gold">超级管理员</Tag>}
            {!text && <Tag>普通用户</Tag>}
        </span>)
    }, {
        title: '操作', fixed: 'right', width: 200, render: (text, record) => (<span>
          <Button type="link" onClick={() => navigate(`/user/detail`, {state: {id: record.id}})}>详情</Button>
          <Button type="link" onClick={() => navigate(`/user/update`, {state: {id: record.id}})} disabled>修改</Button>
            {!record.isFrozen && <Button type="link" onClick={() => putFreezeList(record.id)}>冻结</Button>}
            {!record.isFrozen && <Button type="link" onClick={() => putDisabledList(record.id, true)}>停用</Button>}
            {record.isFrozen && <Button type="link" onClick={() => putDisabledList(record.id, false)}>启用</Button>}
        </span>)
    },];

    const formItemLayout = {
        labelCol: {
            sm: {span: 6},
        }, wrapperCol: {
            sm: {span: 18},
        },
    }

    const inquire = () => {
        getList(1, pageSize)
    }
    const reset = () => {
        form.resetFields();
        getList(1, 10)
    }

    const onTimeChange = (date, dateString) => {
        setCreatedStartTime(dateString[0])
        setCreatedEndTime(dateString[1])
    }

    const navigate = useNavigate();
    const addLink = () => {
        navigate('/user/add')
    }
    return (<>
        <div className='filtrate'>
            <Form {...formItemLayout} form={form}>
                <Row gutter={36}>
                    <Col span={8}>
                        <Form.Item
                            name="username"
                            label="用户名"
                        >
                            <Input placeholder="请输入用户名"/>
                        </Form.Item>
                    </Col>

                    <Col span={8}>
                        <Form.Item
                            name="nickName"
                            label="昵称"
                        >
                            <Input placeholder="请输入昵称"/>
                        </Form.Item>
                    </Col>

                    <Col span={8}>
                        <Form.Item
                            name="email"
                            label="邮箱"
                        >
                            <Input placeholder="请输入邮箱"/>
                        </Form.Item>
                    </Col>


                    <Col span={8}>
                        <Form.Item
                            name="createdTime"
                            label="创建时间"
                        >
                            <RangePicker onChange={onTimeChange} style={{width: '100%'}} format='YYYY-MM-DD'
                                         placeholder="创建日期"/>
                        </Form.Item>
                    </Col>

                    <Col span={16}>
                        <div className='operation'>
                            <Button style={{marginRight: '10px'}} onClick={reset}>重置</Button>
                            <Button type="primary" onClick={inquire}>查询</Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        </div>
        <div className='add'>
            <Button type="primary" onClick={addLink} disabled>新增</Button>
        </div>
        <div>
            <div className='table'>
                <Table rowKey='id' scroll={{x: 2000}} columns={columns} dataSource={list}
                       pagination={false}/>
            </div>

            <div className='pagination'>
                <Pagination
                    showSizeChanger
                    onShowSizeChange={onShowSizeChange}
                    onChange={onChange}
                    showTotal={(total) => `共${total}条记录 第${pageNum}/${Math.ceil(total / pageSize)}页`}
                    total={total}
                    current={pageNum}
                    pageSize={pageSize}
                />
            </div>
        </div>
    </>)
}

export default User